package com.xzmzhp.security;

import com.xzmzhp.pojo.power.Competence;
import com.xzmzhp.service.power.RequestPathService;
import com.xzmzhp.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @author: 王源(xm)
 * @create: 2021-06-08 10:43
 * @program: ams
 * @description: 获取当前请求所需要的权限
 */
@Component
public class FilterInvocationSecurity implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RequestPathService requestPathService;

    /**
     * 匹配规则
     */
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 根据请求路径前缀获取对应权限
     *
     * @param o 路径信息
     * @return 权限信息
     * @throws IllegalArgumentException 安全异常
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取当前url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        //公共路径
        String common = "/common";
        //错误路径
        String error = "/error";

        if (requestUrl.contains(error)) {
            return null;
        }
        String url = requestUrl.substring(0, requestUrl.indexOf("/", 1));
        if (url.equals(common)){
            return null;
        }
        //和数据库匹配
        List<Competence> list = requestPathService.findByOneUrl(url);
        if (StringUtils.isNotNull(list)) {
            //将权限返回
            int count = list.size();
            String[] competence = new String[count];
            for (int i = 0; i < count; i++) {
                competence[i] = list.get(i).getCompetenceName();
            }
            return SecurityConfig.createList(competence);
        }
        //如果不在，则不用返回权限信息。
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
